package com.example.wuqujingdianphone.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;

import com.example.wuqujingdianphone.MyApplication;

import java.util.List;
import java.util.Stack;

/**
 * @author by niuzilin
 * @about : 应用程序Activity管理类：用于Activity管理和应用程序退出
 */
public class AppManager {
    public static final int REFRESH_TIME = 1200;//刷新延迟时间
    public static final int LOAD_MORE_TIME = 600;//加载更多延迟时间
    private static Stack<Activity> activityStack;
    private static AppManager instance;

    public AppManager() {
    }

    /**
     * 单一实例
     */
    public static AppManager getAppManager() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (activityStack.contains(activity)) {
                activityStack.remove(activity);
            }
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        Activity tempActivity = null;
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                tempActivity = activity;
            }
        }

        finishActivity(tempActivity);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 获取界面数量
     *
     * @return activity size
     */
    public static int getActivitySize() {
        if (activityStack != null) {
            return activityStack.size();
        }
        return 0;
    }


    /**
     * 退出应用程序
     */
    @SuppressWarnings("deprecation")
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * 检测安装
     */
    public static boolean checkApp(Context c, String packageName, int versionCode) {
        // 检测当前包名的应用是否安装,检测当前包名的当前版本的应用是否安装
        PackageInfo packageInfo = null;
        try {
            packageInfo = c.getPackageManager().getPackageInfo(packageName, 0);
            if (packageInfo.versionCode == versionCode) {
                return true;
            }
        } catch (NameNotFoundException e) {
            return false;
        }
        return false;
    }

    /**
     * 解析包名下的MainActivity启动路径
     */
    public static String getMainClass(Context c, String packageName) {
        if (!packageName.equals("")) {
            String mainClassName = "";

            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(packageName);
            List<ResolveInfo> activitys = c.getPackageManager().queryIntentActivities(resolveIntent, 0);
            ResolveInfo ri = activitys.iterator().next();
            if (ri != null) {
                mainClassName = ri.activityInfo.name;
            }
            return mainClassName;
        }
        return "";
    }

    /**
     * 获取当前应用的版本号
     */
    public static String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = MyApplication.mContext.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(MyApplication.mContext.getPackageName(), 0);
            return "v" + packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "v1.0";
        }
    }

    /**
     * 跳转到微信
     */
    public static void startWechat(Context context) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.showToast("检查到您手机没有安装微信，请安装后使用该功能");
        }
    }

    /**
     * 跳转到指定包名app
     *
     * @param context
     */
    public static void startApp(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent();
        intent = packageManager.getLaunchIntentForPackage("com.ezaisheng.www");
        if (intent == null) {
            ToastUtil.showToast("检查到您手机没有易再生2.0，请安装后使用该功能");
        } else {
            context.startActivity(intent);
        }
    }

}